package com.tf_cut.backend.seller.service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.UUID;

import javax.annotation.Resource;

import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jcraft.jsch.SftpException;
import com.tf_cut.backend.mapper.SellerAndAccountMapper;
import com.tf_cut.backend.platform.service.RechargeService;
import com.tf_cut.backend.platform.vo.RechargeVo;
import com.tf_cut.backend.request.BkcloudfundsVostroNotifyRequest;
import com.tf_cut.backend.request.CommomRequstHandle;
import com.tf_cut.backend.request.DefaultMybankClient;
import com.tf_cut.backend.request.DefaultSigner;
import com.tf_cut.backend.request.MybankNotifyService;
import com.tf_cut.backend.request.Signer;
import com.tf_cut.backend.request.xml.XmlConverter;
import com.tf_cut.backend.seller.vo.AgentSellerRelation;
import com.tf_cut.backend.seller.vo.RegisterUploadDetailVo;
import com.tf_cut.backend.seller.vo.SellerAndAccountVo;
import com.tf_cut.backend.seller.vo.SellerConfirmMobel;
import com.tf_cut.backend.seller.vo.SellerConfirmVo;
import com.tf_cut.backend.seller.vo.SellerUploadDetailVo;
import com.tf_cut.backend.seller.vo.VostroNotifyModel;
import com.tf_cut.backend.util.ExcelToTxt;
import com.tf_cut.backend.util.HttpUtil;
import com.tf_cut.backend.util.MyConfig;
import com.tf_cut.backend.util.RequestHead;
import com.tf_cut.backend.util.SFTPUtil;
import com.tf_cut.backend.util.SerialNoUtil;

@Service(value = "bkcloudfundsVostroNotifyService")
public class SellerPaymentServiceImpl implements MybankNotifyService {
	
    @Autowired
    private CommomRequstHandle commomRequstHandle;
    
	@Resource
	private SerialNoUtil util;
	
	@Autowired
	private RegisterUploadService registerUploadService;
	
	@Autowired
	private SellerAndAccountMapper sellerAndAccountMapper;
	
	@Autowired
	private SellerUploadDetailService sellerUploadDetailService;
	
//    @Autowired
//    private SellerAccountService sellerAccountService;
    
    @Autowired
    private RechargeService rechargeService;
    
	@Autowired
	private SellerConfirmService sellerConfirmService;
    
    private static Signer signer = new DefaultSigner(MyConfig.privateKey);

	@Override
	public String notifyHandle(String context, String function) throws Exception {
		
		//通知内容转换
        BkcloudfundsVostroNotifyRequest vostroNotifyRequest =
                XmlConverter.getInstance().toResponse(context, BkcloudfundsVostroNotifyRequest.class);
        RequestHead head = vostroNotifyRequest.getBkcloudfundsVostroNotify().getRequestHead();
        //通知内容保存
        boolean flag = saveNotify(vostroNotifyRequest.getBkcloudfundsVostroNotify().getBkcloudfundsVostroNotifyModel());
        
        String jieguo = commomRequstHandle.getSignResult(flag, head);
        System.out.println("返回结果="+jieguo);
        //响应结果根据执行结果统一处理
        return jieguo;
		
	}
	
    private boolean saveNotify(VostroNotifyModel model) {
    	SellerAndAccountVo sellerAndAccountVo = sellerAndAccountMapper.findByMerchantIdRegister(model.getMerchantId());
    	AgentSellerRelation relation = sellerAndAccountMapper.qrySellerR(sellerAndAccountVo.getSellerId());
    	RegisterUploadDetailVo registerUploadDetail = new RegisterUploadDetailVo();
    	String serialNo = util.genSerialNo("C", "A", "3");
    	registerUploadDetail.setUploadId(serialNo);
    	registerUploadDetail.setIsvOrgId(model.getIsvOrgId());
    	registerUploadDetail.setMerchantId(model.getMerchantId());
    	registerUploadDetail.setOutTradeNo(model.getOutTradeNo());
    	registerUploadDetail.setOrderNo(model.getOrderNo());
    	registerUploadDetail.setTransNo(model.getTransNo());
    	registerUploadDetail.setChannelId(model.getChannelId());
    	registerUploadDetail.setPayerBankOrgId(model.getPayerBankOrgId());
    	registerUploadDetail.setPayerCardNo(model.getPayerCardNo());
    	registerUploadDetail.setPayerCardName(model.getPayerCardName());
    	registerUploadDetail.setPayeeCardNo(model.getPayeeCardNo());
    	registerUploadDetail.setPayeeCardName(model.getPayeeCardName());
    	double b = Double.parseDouble(model.getTotalAmount())/100;
    	registerUploadDetail.setTotalAmount(String.valueOf(b));
    	registerUploadDetail.setCurrency(model.getCurrency());
    	registerUploadDetail.setTransferDate(model.getTransferDate());
    	registerUploadDetail.setMemo(model.getMemo());
    	registerUploadDetail.setExtInfo(model.getExtInfo());
    	registerUploadDetail.setStatus(model.getStatus());
    	registerUploadDetail.setVostroType(model.getVostroType());
    	registerUploadDetail.setVostroScene(model.getVostroScene() );
    	registerUploadService.save(registerUploadDetail);
    	SellerUploadDetailVo sellerUploadDetailVo = new SellerUploadDetailVo();
    	sellerUploadDetailVo.setId(serialNo);
    	sellerUploadDetailVo.setInvestSerial(serialNo);
    	sellerUploadDetailVo.setSellerAccountId(relation.getSellerId());
    	sellerUploadDetailVo.setServiceId(sellerAndAccountVo.getServiceId());
    	Double serviceAmount = 0.0;
        if(relation.getServiceFormula() == 1){
        	 serviceAmount = b*relation.getServerAmountPoint()/100/(1+relation.getServerAmountPoint()/100);        	
        }else if(relation.getServiceFormula() == 2){
        	 serviceAmount = b*relation.getServerAmountPoint()/100;
        }else{
        	serviceAmount = b*relation.getServerAmountPoint()/100/(1+relation.getServerAmountPoint()/100);  
        }
        sellerUploadDetailVo.setServiceAmount(serviceAmount);
        sellerUploadDetailVo.setInvestAmount(b);
        sellerUploadDetailVo.setComment(model.getMemo());
        sellerUploadDetailVo.setStatus(0);
        sellerUploadDetailVo.setComment("网商打款");
        sellerUploadDetailVo.setCreateTime(new Date());
        sellerUploadDetailVo.setUpdateTime(new Date());
        sellerUploadDetailService.save(sellerUploadDetailVo);
        
        RechargeVo rechargeVo = new RechargeVo();
        rechargeVo.setId(serialNo);
        rechargeVo.setStatus("1");
        rechargeService.updateRecharge(rechargeVo);
        
        String excel = ExcelToTxt.excelToSellerTxt(registerUploadDetail,sellerUploadDetailVo);
		System.out.println(excel);
		try {
			SFTPUtil.upSftp(excel,serialNo,model.getMerchantId());
		} catch (SftpException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		new DefaultMybankClient(MyConfig.serverUrl, MyConfig.privateKey, MyConfig.mybankPublicKey);
		SellerConfirmMobel SellerConfirm = new SellerConfirmMobel();
		SellerConfirm.setIsvOrgId(MyConfig.isvOrgId);
		SellerConfirm.setMerchantId(sellerAndAccountVo.getMerchantId());
		SellerConfirm.setOutTradeNo(UUID.randomUUID().toString().replace("-", ""));
		SellerConfirm.setBatchNo(serialNo);
		//SellerConfirm.setRelateBatchNo("");
		double sum = sellerUploadDetailVo.getServiceAmount() * 100;
		SellerConfirm.setTotalAmount((int)sum);
		SellerConfirm.setPayerCardNo(sellerAndAccountVo.getBankCardNo());
		SellerConfirm.setTotalFeeAmount(0);
		SellerConfirm.setCurrency("CNY");
		SellerConfirm.setTotalCount(1);
		SellerConfirm.setPayWay("01");
		SellerConfirm.setPayrollCreditType("02");
		SellerConfirm.setMemo("");
		// 采用非注解方式将对象转xml
		String resultXml = MyConfig.beanToXml(SellerConfirm, "ant.mybank.bkcloudfunds.comanagement.file.confirm");
		System.out.println("对象转码" + resultXml);
		String sellerRegisterVoXml;
		String IsvOrgId = null;
		String MerchantId = null;
		String OutTradeNo = null;
		String BatchNo = null;
		String resultStatus = null;
		String resultCode = null;
		String resultMsg = null;
		try {
			sellerRegisterVoXml = signer.sign(resultXml, MyConfig.charset, MyConfig.signType);
			String response = HttpUtil.doPosts(MyConfig.serverUrl, sellerRegisterVoXml, "UTF-8");
			System.out.println("商户入驻查询返回响应报文：" + response);
			SAXReader reader = new SAXReader();
			try {
				org.dom4j.Document doc = reader.read(new ByteArrayInputStream(response.getBytes("UTF-8")));
				org.dom4j.Element root = doc.getRootElement();
				org.dom4j.Element element;
				org.dom4j.Element element2;
				org.dom4j.Element element3;
				for (Iterator i = root.elementIterator("response"); i.hasNext();) {
					element = (org.dom4j.Element) i.next();
					for (Iterator j = element.elementIterator("body"); j.hasNext();) {
						element2 = (org.dom4j.Element) j.next();
						for (Iterator k = element2.elementIterator("RespInfo"); k.hasNext();) {
							element3 = (org.dom4j.Element) k.next();
							resultStatus = element3.elementText("ResultStatus");
							resultCode = element3.elementText("ResultCode");
							resultMsg = element3.elementText("ResultMsg");
						}
						IsvOrgId = element2.elementText("IsvOrgId");
						MerchantId = element2.elementText("MerchantId");
						OutTradeNo = element2.elementText("OutTradeNo");
						BatchNo = element2.elementText("BatchNo");
					}
				}
				SellerConfirmVo sellerConfirm = new SellerConfirmVo();
				sellerConfirm.setId(UUID.randomUUID().toString().replace("-", ""));
				sellerConfirm.setMerchantId(MerchantId);
				sellerConfirm.setOrderId(serialNo);
				sellerConfirm.setOutTradeNo(OutTradeNo);
				sellerConfirm.setBatchNo(BatchNo);
				sellerConfirm.setRelateBatchNo("");
				sellerConfirm.setResultStatus(resultStatus);
				sellerConfirm.setResultCode(resultCode);
				sellerConfirm.setResultMsg(resultMsg);
				sellerConfirm.setIsvOrgId(IsvOrgId);
				sellerConfirm.setAskTime(new Timestamp(System.currentTimeMillis()));
				sellerConfirmService.save(sellerConfirm);
			} catch (Exception e) {
			}
		} catch (Exception e) {
		}
        
        
        return true;
    }

}
